import React, { useState } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, DatePicker, Space, Tag, message, Row, Col, Calendar, Badge } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, CalendarOutlined, VideoCameraOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker
const { Option } = Select
const { TextArea } = Input

export default function MeetingRooms() {
  const [rooms, setRooms] = useState([
    {
      id: 1,
      name: '会议室A',
      capacity: 10,
      location: 'A区2楼',
      equipment: ['投影仪', '白板', '视频会议'],
      status: 'available',
      currentBooking: null
    },
    {
      id: 2,
      name: '会议室B',
      capacity: 20,
      location: 'B区3楼',
      equipment: ['投影仪', '音响', '白板'],
      status: 'occupied',
      currentBooking: {
        title: '项目评审会',
        organizer: '张经理',
        time: '14:00-16:00'
      }
    }
  ])

  const [bookings, setBookings] = useState([
    {
      id: 1,
      roomId: 1,
      roomName: '会议室A',
      title: '周例会',
      organizer: '李经理',
      participants: ['张三', '李四', '王五'],
      startTime: '2024-01-15 09:00',
      endTime: '2024-01-15 10:00',
      status: 'confirmed',
      description: '讨论本周工作进展'
    },
    {
      id: 2,
      roomId: 2,
      roomName: '会议室B',
      title: '项目评审会',
      organizer: '张经理',
      participants: ['陈工程师', '王主管', '刘总监'],
      startTime: '2024-01-15 14:00',
      endTime: '2024-01-15 16:00',
      status: 'confirmed',
      description: '新产品项目评审'
    }
  ])

  const [activeTab, setActiveTab] = useState('rooms')
  const [modalVisible, setModalVisible] = useState(false)
  const [bookingModalVisible, setBookingModalVisible] = useState(false)
  const [editingRecord, setEditingRecord] = useState(null)
  const [selectedDate, setSelectedDate] = useState(dayjs())
  const [form] = Form.useForm()
  const [bookingForm] = Form.useForm()

  const statusColors = {
    available: 'green',
    occupied: 'red',
    maintenance: 'orange'
  }

  const statusTexts = {
    available: '可用',
    occupied: '占用中',
    maintenance: '维护中'
  }

  const bookingStatusColors = {
    confirmed: 'green',
    pending: 'orange',
    cancelled: 'red'
  }

  const bookingStatusTexts = {
    confirmed: '已确认',
    pending: '待确认',
    cancelled: '已取消'
  }

  const roomColumns = [
    {
      title: '会议室名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '容量',
      dataIndex: 'capacity',
      key: 'capacity',
      render: (capacity) => `${capacity}人`,
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '设备',
      key: 'equipment',
      render: (_, record) => (
        <div>
          {record.equipment.map(item => (
            <Tag key={item} size="small">{item}</Tag>
          ))}
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <div>
          <Tag color={statusColors[record.status]}>
            {statusTexts[record.status]}
          </Tag>
          {record.currentBooking && (
            <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
              {record.currentBooking.title} ({record.currentBooking.time})
            </div>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<CalendarOutlined />}
            onClick={() => handleBookRoom(record)}
            disabled={record.status === 'maintenance'}
          >
            预订
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEditRoom(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteRoom(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const bookingColumns = [
    {
      title: '会议主题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '会议室',
      dataIndex: 'roomName',
      key: 'roomName',
    },
    {
      title: '组织者',
      dataIndex: 'organizer',
      key: 'organizer',
    },
    {
      title: '时间',
      key: 'time',
      render: (_, record) => (
        <div>
          <div>{dayjs(record.startTime).format('MM-DD HH:mm')}</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            至 {dayjs(record.endTime).format('HH:mm')}
          </div>
        </div>
      ),
    },
    {
      title: '参与人员',
      key: 'participants',
      render: (_, record) => (
        <div>
          {record.participants.slice(0, 2).map(name => (
            <Tag key={name} size="small">{name}</Tag>
          ))}
          {record.participants.length > 2 && (
            <Tag size="small">+{record.participants.length - 2}</Tag>
          )}
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Tag color={bookingStatusColors[record.status]}>
          {bookingStatusTexts[record.status]}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEditBooking(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteBooking(record.id)}
          >
            取消
          </Button>
        </Space>
      ),
    },
  ]

  const handleBookRoom = (room) => {
    bookingForm.setFieldsValue({ roomId: room.id, roomName: room.name })
    setBookingModalVisible(true)
  }

  const handleEditRoom = (record) => {
    setEditingRecord(record)
    form.setFieldsValue(record)
    setModalVisible(true)
  }

  const handleDeleteRoom = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确认删除这个会议室吗？',
      onOk: () => {
        setRooms(prev => prev.filter(item => item.id !== id))
        message.success('删除成功')
      }
    })
  }

  const handleEditBooking = (record) => {
    setEditingRecord(record)
    bookingForm.setFieldsValue({
      ...record,
      timeRange: [dayjs(record.startTime), dayjs(record.endTime)]
    })
    setBookingModalVisible(true)
  }

  const handleDeleteBooking = (id) => {
    Modal.confirm({
      title: '确认取消',
      content: '确认取消这个会议预订吗？',
      onOk: () => {
        setBookings(prev => prev.filter(item => item.id !== id))
        message.success('取消成功')
      }
    })
  }

  const handleSubmitRoom = async (values) => {
    try {
      if (editingRecord) {
        setRooms(prev => 
          prev.map(item => 
            item.id === editingRecord.id ? { ...item, ...values } : item
          )
        )
        message.success('更新成功')
      } else {
        const newRoom = {
          id: Date.now(),
          ...values,
          status: 'available',
          currentBooking: null
        }
        setRooms(prev => [...prev, newRoom])
        message.success('添加成功')
      }
      setModalVisible(false)
      form.resetFields()
      setEditingRecord(null)
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleSubmitBooking = async (values) => {
    try {
      const formattedValues = {
        ...values,
        startTime: values.timeRange[0].format('YYYY-MM-DD HH:mm'),
        endTime: values.timeRange[1].format('YYYY-MM-DD HH:mm'),
        participants: values.participants.split(',').map(p => p.trim())
      }
      delete formattedValues.timeRange

      if (editingRecord) {
        setBookings(prev => 
          prev.map(item => 
            item.id === editingRecord.id ? { ...item, ...formattedValues } : item
          )
        )
        message.success('更新成功')
      } else {
        const newBooking = {
          id: Date.now(),
          ...formattedValues,
          status: 'confirmed'
        }
        setBookings(prev => [...prev, newBooking])
        message.success('预订成功')
      }
      setBookingModalVisible(false)
      bookingForm.resetFields()
      setEditingRecord(null)
    } catch (error) {
      message.error('操作失败')
    }
  }

  const getListData = (value) => {
    const dateStr = value.format('YYYY-MM-DD')
    return bookings.filter(booking => 
      dayjs(booking.startTime).format('YYYY-MM-DD') === dateStr
    ).map(booking => ({
      type: 'success',
      content: `${booking.title} (${booking.roomName})`
    }))
  }

  const dateCellRender = (value) => {
    const listData = getListData(value)
    return (
      <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {listData.map((item, index) => (
          <li key={index}>
            <Badge status={item.type} text={item.content} />
          </li>
        ))}
      </ul>
    )
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Row gutter={16}>
          <Col span={16}>
            <Card 
              title="会议室管理"
              tabList={[
                { key: 'rooms', tab: '会议室列表' },
                { key: 'bookings', tab: '预订记录' }
              ]}
              activeTabKey={activeTab}
              onTabChange={setActiveTab}
              extra={
                <Space>
                  {activeTab === 'rooms' && (
                    <Button 
                      type="primary" 
                      icon={<PlusOutlined />}
                      onClick={() => {
                        setEditingRecord(null)
                        form.resetFields()
                        setModalVisible(true)
                      }}
                    >
                      新增会议室
                    </Button>
                  )}
                  {activeTab === 'bookings' && (
                    <Button 
                      type="primary" 
                      icon={<CalendarOutlined />}
                      onClick={() => {
                        setEditingRecord(null)
                        bookingForm.resetFields()
                        setBookingModalVisible(true)
                      }}
                    >
                      新增预订
                    </Button>
                  )}
                </Space>
              }
            >
              {activeTab === 'rooms' && (
                <Table
                  columns={roomColumns}
                  dataSource={rooms}
                  rowKey="id"
                  pagination={false}
                />
              )}
              {activeTab === 'bookings' && (
                <Table
                  columns={bookingColumns}
                  dataSource={bookings}
                  rowKey="id"
                  pagination={false}
                />
              )}
            </Card>
          </Col>
          
          <Col span={8}>
            <Card title="会议日历" size="small">
              <Calendar 
                fullscreen={false}
                dateCellRender={dateCellRender}
                onSelect={setSelectedDate}
              />
            </Card>
          </Col>
        </Row>

        {/* 会议室编辑模态框 */}
        <Modal
          title={editingRecord ? '编辑会议室' : '新增会议室'}
          open={modalVisible}
          onOk={() => form.submit()}
          onCancel={() => setModalVisible(false)}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmitRoom}
          >
            <Form.Item name="name" label="会议室名称" rules={[{ required: true }]}>
              <Input placeholder="请输入会议室名称" />
            </Form.Item>
            <Form.Item name="capacity" label="容量" rules={[{ required: true }]}>
              <Input type="number" placeholder="请输入容量" addonAfter="人" />
            </Form.Item>
            <Form.Item name="location" label="位置" rules={[{ required: true }]}>
              <Input placeholder="请输入位置" />
            </Form.Item>
            <Form.Item name="equipment" label="设备">
              <Select mode="multiple" placeholder="请选择设备">
                <Option value="投影仪">投影仪</Option>
                <Option value="白板">白板</Option>
                <Option value="音响">音响</Option>
                <Option value="视频会议">视频会议</Option>
                <Option value="电话会议">电话会议</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        {/* 预订模态框 */}
        <Modal
          title={editingRecord ? '编辑预订' : '新增预订'}
          open={bookingModalVisible}
          onOk={() => bookingForm.submit()}
          onCancel={() => setBookingModalVisible(false)}
          width={600}
        >
          <Form
            form={bookingForm}
            layout="vertical"
            onFinish={handleSubmitBooking}
          >
            <Form.Item name="roomId" label="会议室" rules={[{ required: true }]}>
              <Select placeholder="请选择会议室">
                {rooms.map(room => (
                  <Option key={room.id} value={room.id}>
                    {room.name} (容量: {room.capacity}人)
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="title" label="会议主题" rules={[{ required: true }]}>
              <Input placeholder="请输入会议主题" />
            </Form.Item>
            <Form.Item name="organizer" label="组织者" rules={[{ required: true }]}>
              <Input placeholder="请输入组织者" />
            </Form.Item>
            <Form.Item name="timeRange" label="会议时间" rules={[{ required: true }]}>
              <RangePicker 
                showTime 
                format="YYYY-MM-DD HH:mm"
                style={{ width: '100%' }}
              />
            </Form.Item>
            <Form.Item name="participants" label="参与人员" rules={[{ required: true }]}>
              <Input placeholder="请输入参与人员，用逗号分隔" />
            </Form.Item>
            <Form.Item name="description" label="会议描述">
              <TextArea rows={3} placeholder="请输入会议描述" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </Layout>
  )
}